


//
//  BADataHandle.m
//  BabyAlbum
//
//  Created by master on 17/2/14.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BADataHandle.h"
#import <FMDB/FMDB.h>
#import "BAResource.h"

#define BA_PATH_DB [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"ia.db"]

@interface BADataHandle ()

@property (nonatomic,strong) FMDatabase *db;
@property (nonatomic,strong) FMDatabaseQueue *dbQueue;

@end

static NSString *DB_TABLE_ALBUM = @"ba_album";
static NSString *DB_TABLE_RESOURSE = @"ba_resource";
static NSString *DB_K1_AlbumId = @"albumId";
static NSString *DB_K1_CoverName = @"cover_name";
static NSString *DB_K1_CoverIsPic = @"is_pic";

static NSString *DB_K1_Title = @"title";
static NSString *DB_K1_Desc = @"desc";
static NSString *DB_K1_MoreDesc = @"more_desc";
static NSString *DB_K1_Cre_Date = @"create_date";
static NSString *DB_K1_Cus_Date = @"custom_date";
static NSString *DB_K1_Update_Date = @"update_date";
static NSString *DB_K1_Order = @"resource_order";

static NSString *DB_K2_id = @"id";
static NSString *DB_K2_AlbumId = @"albumId";
static NSString *DB_K2_Name = @"name";
static NSString *DB_K2_IsPic = @"is_pic";
//static NSString *DB_K2_TS = @"ts";

//static NSString *DB_K_Cover = @"cover";
//static NSString *DB_K_Cover = @"cover";
//static NSString *DB_K_Cover = @"cover";
//static NSString *DB_K_Cover = @"cover";
//static NSString *DB_K_Cover = @"cover";
//static NSString *DB_K_Cover = @"cover";

// 数据库可能出现
@implementation BADataHandle

+ (instancetype)shareInstance {
    static BADataHandle *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!handle) {
            handle = [[BADataHandle alloc] init];
        }
    });
    return handle;
}

- (instancetype) init {
    self = [super init];
    self.db = [FMDatabase databaseWithPath:BA_PATH_DB];
    self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:BA_PATH_DB];
    
    if([self.db open]) {
        NSLog(@"打开数据库成功--%@",BA_PATH_DB);
    }
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        
        NSString *sql = [NSString stringWithFormat:@"create table if not exists %@ (%@ text primary key,%@ text,%@ text,%@ text,%@ text,%@ integer,%@ bool,%@ integer,%@ integer,%@ text)",DB_TABLE_ALBUM,DB_K1_AlbumId,DB_K1_CoverName,DB_K1_Title,DB_K1_Desc,DB_K1_MoreDesc,DB_K1_Cre_Date,DB_K1_CoverIsPic,DB_K1_Cus_Date,DB_K1_Update_Date,DB_K1_Order];
        [self.db executeUpdate:sql];
        sql = [NSString stringWithFormat:@"create table if not exists %@ (%@ integer primary key autoincrement,%@ text,%@ text,%@ bool)",DB_TABLE_RESOURSE,DB_K2_id,DB_K2_AlbumId,DB_K2_Name,DB_K2_IsPic];
        [self.db executeUpdate:sql];
    }];
    return self;
}

- (void)deleteAlbum:(BAAlbumModel *)model {
    if(!model.album_id || !model.album_id.length) {
        NSLog(@"相册ID为空,删除相册失败");
    }
    [self deleteAllResourceIn:model.album_id];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@='%@'",DB_TABLE_ALBUM,DB_K1_AlbumId,model.album_id];
        [db executeUpdate:sql];
    }];
}

- (void)createAlbumWithModel:(BAAlbumModel *)model {
    model.album_id = [self albumIdGenerate];
    // 插入资源表
    [self insertResource:model.resourceList to:model.album_id];
    model.cover.name = [BAResource writeResource:model.cover];
    
    model.create_date = BATimeStamp;
    model.update_date = BATimeStamp;
    
    // 生成相册行
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"insert into %@ (%@,%@,%@,%@,%@,%@,%@,%@,%@) values ('%@','%@','%@','%@','%@',%@,%d,%@,%@)",DB_TABLE_ALBUM,
                         DB_K1_AlbumId,DB_K1_CoverName,DB_K1_Title,DB_K1_Desc,DB_K1_MoreDesc,DB_K1_Cre_Date,DB_K1_CoverIsPic,DB_K1_Update_Date,DB_K1_Cus_Date,
                         model.album_id,model.cover.name,model.title,model.desc,model.more_desc,model.create_date,model.cover.type == BAResourceTypeImage,model.create_date,model.custom_date];
        [self.db executeUpdate:sql];
    }];
}

- (NSArray<BAAlbumModel *> *)allAlbums {
    NSString *sql = [NSString stringWithFormat:@"select * from %@ ",DB_TABLE_ALBUM];
    
    FMResultSet *res = [self.db executeQuery:sql];
    NSMutableArray *list = [NSMutableArray array];
    while ([res next]) {
        BAAlbumModel *model = [[BAAlbumModel alloc] init];
        model.album_id = [res stringForColumn:DB_K1_AlbumId];
        BOOL isVideoCover = ![res boolForColumn:DB_K1_CoverIsPic];
//        model.cover_name = [res stringForColumn:DB_K1_CoverName];
        BAAlbumItem *item ;
        if(isVideoCover) {
            item = [[BAAlbumVideoItem alloc] init];
        } else {
            item = [[BAAlbumImageItem alloc] init];
        }
        item.name = [res stringForColumn:DB_K1_CoverName];
        model.cover = [item autoFetch];
        model.title = [[[res stringForColumn:DB_K1_Title] uxy_URLDecoding] safeOutString];
        model.desc = [[[res stringForColumn:DB_K1_Desc] uxy_URLDecoding] safeOutString];
        model.more_desc = [[res stringForColumn:DB_K1_MoreDesc] safeOutString];
        model.create_date = [[res stringForColumn:DB_K1_Cre_Date] safeOutString];
        model.custom_date = [[res stringForColumn:DB_K1_Cus_Date] safeOutString];
        model.update_date = [[res stringForColumn:DB_K1_Update_Date] safeOutString];
        [list addObject:model];
    }
    return [list copy];
}

- (NSString *)albumIdGenerate {
    NSUUID *uuid = [NSUUID UUID];
    return [uuid UUIDString];
}

- (NSArray<BAAlbumItem *> *)resourceInAlbum:(NSString *)albumId {
    if(!albumId.length) {
        return @[];
    } else {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@='%@'",DB_TABLE_RESOURSE,DB_K2_AlbumId,albumId];
        FMResultSet *res = [self.db executeQuery:sql];
        NSMutableArray *list = [NSMutableArray array];
        
        while ([res next]) {
            BOOL isPic = [res boolForColumn:DB_K2_IsPic];
            NSString *name = [res stringForColumn:DB_K2_Name];
            BAAlbumItem *item ;
            if(isPic) {
               item = [[BAAlbumImageItem alloc] init];
            } else {
                item = [[BAAlbumVideoItem alloc] init];
            }
            item.name = name;

            [list addObject:item];
        }
        return list;
        
    }
}

- (void)updateAlbumDataWithModel:(BAAlbumModel *)model {
    if(!model.album_id.length) {
        [self createAlbumWithModel:model];
    }else {
        // 删除原来的 <表2>
        [self deleteAllResourceIn:model.album_id];
        
        //添加现在的 <表2po>
        [self insertResource:model.resourceList to:model.album_id];
        
        model.cover.name =[BAResource writeResource:model.cover];
        model.update_date = BATimeStamp;
        //更新最新的相册封面内容 (表1)
        [self.dbQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"update %@ set %@='%@',%@='%@',%@='%@',%@=%d,%@=%@,%@=%@ where %@='%@'",
                             DB_TABLE_ALBUM,
                             DB_K1_CoverName,model.cover.name,
                             DB_K1_Title,[model.title uxy_URLEncoding],
                             DB_K1_Desc,[model.desc uxy_URLEncoding],
                             DB_K1_CoverIsPic, model.cover.type == BAResourceTypeImage,
                             DB_K1_Update_Date,model.update_date,
                             DB_K1_Cus_Date,model.custom_date,
                             DB_K1_AlbumId,model.album_id
                             ];
            [self.db executeUpdate:sql];
        }];
    }
}

//TODO: 需要删除路径下的图片
- (void)deleteAllResourceIn:(NSString *)albumId {
    NSArray *resourceList = [self resourceInAlbum:albumId];
    // 延时清除视频.保证视频在被重新拷贝后删除
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (BAAlbumItem *resoruce in resourceList) {
            [BAResource deleteResource:resoruce];
        }
    });
   
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
       NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@='%@'",
                        DB_TABLE_RESOURSE,
                        DB_K2_AlbumId,
                        albumId
                        ];
        [db executeUpdate:sql];
    }];
}

- (void)insertResource:(NSArray<BAAlbumItem *> *)resourceList to:(NSString *)albumId {
    //无图
    if(!resourceList.count) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where %@='%@'",DB_TABLE_RESOURSE,DB_K2_AlbumId,albumId];
        [self.dbQueue inDatabase:^(FMDatabase *db) {
            [db executeUpdate:sql];
        }];

    }else {
        NSString *sql = [NSString stringWithFormat:@"insert into %@ ('%@','%@',%@)",
                         DB_TABLE_RESOURSE,
                         DB_K2_AlbumId,DB_K2_Name,DB_K2_IsPic
                         //                         albumId,      imageName, @"1"
                         ];
        NSMutableString *values = [NSMutableString string];
        for (BAAlbumItem *item in resourceList) {
            if(!values.length) {
                [values appendString:@" select "];
            } else {
                [values appendString:@" union all select "];
            }
            NSString *name = [BAResource writeResource:item];
            [values appendFormat:@"'%@','%@',%d",albumId,name,[item isKindOfClass:[BAAlbumImageItem class]]];
        }
        sql = [NSString stringWithFormat:@"%@ %@",sql,values];
        
        [self.dbQueue inDatabase:^(FMDatabase *db) {
            [db executeUpdate:sql];
        }];

    }
    
}

//- (void)insertAlbumWithModel:(BAAlbumModel *)model {
//    NSString *sql = [NSString stringWithFormat:@"insert into %@ (%@,%@,%@,%@) values (%@,'%@','%@',%@)",DB_TABLE_ALBUM,DB_K1_CoverName,DB_K1_Title,DB_K1_Des,DB_K1_TS,model.cover_id,model.title,model.detailDesc,model.date];
//    [self.db executeUpdate:sql];
//}
//- (void)

@end
